package com.compass.doctor.ui.prescription.fragment

import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.compass.doctor.R
import com.compass.doctor.base.BaseVBFragment
import com.compass.doctor.callback.OnCustomButtonClick
import com.compass.doctor.callback.OnScreenPrescriptionCallBack
import com.compass.doctor.callback.RxCancellationCallBack
import com.compass.doctor.databinding.FragmentHistoryPrescriptionBinding
import com.compass.doctor.dialog.CancellationDialog
import com.compass.doctor.dialog.ScreenPrescriptionDialog
import com.compass.doctor.ui.WebDetailActivity
import com.compass.doctor.ui.patient.adapter.PrescribedAdapter
import com.compass.doctor.ui.prescription.viewmodel.PrescribeViewModel
import com.compass.framework.constant.KEY_ORDER_TYPE
import com.compass.framework.constant.RX_DETAILS
import com.compass.framework.decoration.NormalItemDecoration
import com.compass.framework.ext.gone
import com.compass.framework.ext.load
import com.compass.framework.ext.onClick
import com.compass.framework.ext.toBeanOrNull
import com.compass.framework.ext.visible
import com.compass.framework.manager.DictionariesManager
import com.compass.framework.model.Dictionaries
import com.compass.framework.model.ScreenTag
import com.compass.framework.utils.BigDecimalUtils
import com.compass.framework.utils.dpToPx
import com.compass.framework.utils.getStringFromResource
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener
import com.scwang.smart.refresh.layout.listener.OnRefreshListener

/**
 * Description： 历史处方
 * Date:2023/12/19 10:23
 */
class HistoryPrescriptionFragment : BaseVBFragment<FragmentHistoryPrescriptionBinding>(), OnLoadMoreListener,
    OnRefreshListener {
    private var dictionariesList: ArrayList<Dictionaries> = ArrayList()
    private var statusTime: ArrayList<ScreenTag> = ArrayList()
    private val prescribeViewModel: PrescribeViewModel by viewModels()
    private lateinit var prescribedAdapter: PrescribedAdapter
    private var mPage = 1
    private var statusValue:ArrayList<String> =ArrayList()
    private var startDateValue:Long?=null
    private var endDateValue:Long?=null
    private var orderType: Int = 1
    private var cancellationDialog: CancellationDialog.Builder? = null

    private var rxCancellationCallBack :RxCancellationCallBack =object :RxCancellationCallBack{
        override fun onCancellationCallBack(orderId: String, suggest: String?) {
            cancellationDialog?.dismissDialog()
            showLoading()
            prescribeViewModel.prescriptionCancel(orderId, suggest)
        }
    }

    override fun initView(view: View, savedInstanceState: Bundle?) {
        arguments?.let {
            orderType = it.getInt(KEY_ORDER_TYPE)
        }
        dictionariesList = DictionariesManager.getOrderStatusJson()?.toBeanOrNull<MutableList<Dictionaries>>() as ArrayList<Dictionaries>
        statusTime.add(ScreenTag("1", "本日", false))
        statusTime.add(ScreenTag("2", "本周", false))
        statusTime.add(ScreenTag("3", "本月", false))
        statusTime.add(ScreenTag("4", "自定义", false))
        initRecyclerView()
    }

    private fun initRecyclerView() {
        mBinding?.refreshLayout?.apply {
            setEnableRefresh(true)
            setEnableLoadMore(true)
            setOnRefreshListener(this@HistoryPrescriptionFragment)
            setOnLoadMoreListener(this@HistoryPrescriptionFragment)
        }
        prescribedAdapter = PrescribedAdapter()
        val dp10 = dpToPx(10)
        mBinding?.recyclerView?.apply {
            layoutManager = LinearLayoutManager(context)
            addItemDecoration(NormalItemDecoration().apply {
                setBounds(left = dp10, top = dp10, right = dp10, bottom = dp10)
                setLastBottom(true)
            })
            adapter = prescribedAdapter
        }

        prescribedAdapter.setBottomCallBack(object : OnCustomButtonClick{
            override fun onButtonCallBack(position: Int, msgType: String?) {
                val item=prescribedAdapter.getItem(position)

                when(msgType){
                    "cancellation"->{
                        item?.let {details->
                            cancellationDialog= CancellationDialog.Builder(requireActivity(), details.id,rxCancellationCallBack)
                            cancellationDialog?.show()
                        }
                    }

                    "details"->{
                        item?.let {details->
                            if (details.isTransfer=="1"){
                                showToast(getStringFromResource(R.string.prescribed_tips))

                            }else{
                                WebDetailActivity.start(
                                    context = requireActivity(),
                                    url = RX_DETAILS +details.id,
                                    title ="处方详情"
                                )
                            }



                        }
                    }
                }
            }
        })


    }

    override fun intListener() {
        mBinding?.tvScreen?.onClick {

            ScreenPrescriptionDialog.Builder(requireActivity(),dictionariesList,statusTime,object :OnScreenPrescriptionCallBack{
                override fun onScreenPrescriptionSave( statusList:ArrayList<String>,startDate: Long?, endDate: Long? ,dictionaries: ArrayList<Dictionaries>) {
                    mPage = 1
                    dictionariesList=dictionaries
                    statusValue=statusList
                    startDateValue=startDate
                    endDateValue=endDate
                    getPrescribedList()
                }
            }).show()
        }
    }

    override fun initData() {
        showLoading()

        prescribeViewModel.getHisPrescriptionTotal(statusValue,startDateValue,endDateValue)
        getPrescribedList()
        prescribeViewModel.historyPrescriptionLiveData.observe(this) {
            dismissLoading()
            if (mPage == 1) {
                prescribedAdapter.setData(it)
                mBinding?.refreshLayout?.finishRefresh()
                mBinding?.refreshLayout?.setEnableLoadMore(load(it?.size))
                if (it.isNullOrEmpty()) {
                    mBinding?.emptyView?.visible()
                } else {
                    mBinding?.emptyView?.gone()
                }
            } else {
                mBinding?.refreshLayout?.finishLoadMore()
                if (!it.isNullOrEmpty()) {
                    prescribedAdapter.addAll(it)
                } else {
                    mBinding?.refreshLayout?.setEnableLoadMore(false)
                }
            }
        }
        prescribeViewModel.cancelLiveData.observe(this){
          dismissLoading()
            getPrescribedList()
        }
        prescribeViewModel.historyPrescriptionTotalLiveData.observe(this) {
            it?.let {total->
                mBinding?.tvAmount?.text = "处方总金额：${BigDecimalUtils.divide(total)}元"

            }
        }
    }


    private fun getPrescribedList() {
        prescribeViewModel.getHisPrescription(mPage,"",statusValue,startDateValue,endDateValue,null,null)

    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        mPage++
        getPrescribedList()
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        mPage = 1
        getPrescribedList()
    }
}